package com.platform.config;

import com.platform.uaa.enhancer.JwtTokenEnhancer;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务器配置
 *
 * @author zyk
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

  private final UserDetailsService customUserDetailsService;
  private final ClientDetailsService customClientDetailsService;
  private final AuthenticationManager authenticationManager;
  private final JwtTokenEnhancer jwtTokenEnhancer;

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(customClientDetailsService);
  }

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    //配置JWT的内容增强器
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    List<TokenEnhancer> delegates = new ArrayList<>();
    delegates.add(jwtTokenEnhancer);
    delegates.add(jwtAccessTokenConverter());
    enhancerChain.setTokenEnhancers(delegates);

    endpoints//密码模式必要配置
            .authenticationManager(authenticationManager)
            // 获取用户信息接口
            .userDetailsService(customUserDetailsService)
            // 配置增强器
            .tokenEnhancer(enhancerChain)
            .accessTokenConverter(jwtAccessTokenConverter())
            // 默认为true，true重复使用（刷新token过期时间不变），false非重复使用（刷新过期时间也刷新）
            .reuseRefreshTokens(false)
            // /支持GET,POST请求
            .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);

  }

  /**
   *  允许表单认证
   * @param security
   */
  @Override
  public void configure(AuthorizationServerSecurityConfigurer security) {
    security.allowFormAuthenticationForClients();
  }

  /**
   *  jwt token转换器
   * @return
   */
  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setKeyPair(keyPair());
    return jwtAccessTokenConverter;
  }

  /**
   *  从秘钥库提取秘钥 私钥&公钥
   * @return
   */
  @Bean
  public KeyPair keyPair() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("/kingdee.jks"), "kingdee2021".toCharArray());
    return keyStoreKeyFactory.getKeyPair("kingdee", "kingdee2021".toCharArray());
  }

}
